﻿using System;
using System.IO;
using System.Text;
using NLog;

namespace Com.Lancetinc.Evs.Helpers
{
    /// <summary>
    /// 用于写Json格式的配置文件
    /// 先写到临时文件再复制
    /// </summary>
    public static class JsonConfigUtil
    {
        public static void Write<T>(string file, T config)
        {
            var json = JsonUtil.Stringify(config, true);
            FileUtil.EnsureDirectoryExists(file);

            FileUtil.WriteAllText(file, json);
        }

        public static object Read(string file, Type type)
        {
            var json = File.ReadAllText(file, Encoding.UTF8);
            if (string.IsNullOrEmpty(json))
            {
                return default;
            }

            try
            {
                return JsonUtil.Parse(json, type);
            }
            catch (Exception e)
            {
                LogManager.GetCurrentClassLogger().Error(e);
                return default;
            }
        }

        public static T Read<T>(string file)
        {
            var json = File.ReadAllText(file, Encoding.UTF8);
            if (string.IsNullOrEmpty(json))
            {
                return default;
            }

            try
            {
                return JsonUtil.Parse<T>(json);
            }
            catch (Exception e)
            {
                LogManager.GetCurrentClassLogger().Error(e);
                return default;
            }
        }
    }
}
